package cn.edu.gznu.wecampus.core.auth;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import cn.edu.gznu.wecampus.core.ApplicationContextHolder;
import cn.edu.gznu.wecampus.core.common.entity.jpa.User;
import cn.edu.gznu.wecampus.core.common.repository.jpa.UserRepository;
import cn.edu.gznu.wecampus.core.service.PropertyService;
import cn.edu.gznu.wecampus.core.utils.JwtUtils;
import cn.edu.gznu.wisedu.entity.ldap.Member;
import cn.edu.gznu.wisedu.repository.ldap.MemberRepository;

public class JwtRealm extends AuthorizingRealm {
	
	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof JwtToken;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userId = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		PropertyService propertyService = ApplicationContextHolder.getBean(PropertyService.class);
		String jwtToken = (String) token.getCredentials();
		if(StringUtils.isEmpty(jwtToken)) {
			throw new AuthenticationException(
				propertyService.getProperty("pointcircle.framework.message.auth.token-invalid")
			);
		}
		String userId = JwtUtils.getUserId(jwtToken);
		if(StringUtils.isEmpty(userId)) {
			throw new AuthenticationException(
				propertyService.getProperty("pointcircle.framework.message.auth.token-invalid")
			);
		}
		//首先匹配内置用户
		UserRepository userRepository = ApplicationContextHolder.getBean(UserRepository.class);
		User user = userRepository.findByUsername(userId);
		if(user != null) {
			if(!JwtUtils.verify(jwtToken, userId)) {
				throw new AuthenticationException(
					propertyService.getProperty("pointcircle.framework.message.auth.token-invalid")
				);
			}
			return new SimpleAuthenticationInfo(userId, jwtToken, getName());
		}
		//其次匹配LDAP用户
		MemberRepository memberRepository = ApplicationContextHolder.getBean(MemberRepository.class);
		Member member = memberRepository.findByXgh(userId);
		if(member != null) {
			if(!JwtUtils.verify(jwtToken, userId)) {
				throw new AuthenticationException(
					propertyService.getProperty("pointcircle.framework.message.auth.token-invalid")
				);
			}
			return new SimpleAuthenticationInfo(userId, jwtToken, getName());
		}
		throw new AuthenticationException(
			propertyService.getProperty("pointcircle.framework.message.auth.token-invalid")
		);
	}
	
}
